package com.bangdao.app.jetpacktest.jetpack.livedata;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.bangdao.app.jetpacktest.R;

public class TimerWithLiveDataActivity extends AppCompatActivity {

    private MutableLiveData<Integer> liveData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer_with_live_data);

        initComponent();
    }

    private void initComponent() {
        //通过ViewModelProvider得到ViewModel
        TimerWithLiveDataViewModel timerWithLiveDataViewModel = new ViewModelProvider(this)
                .get(TimerWithLiveDataViewModel.class);

        //得到ViewModel中的LiveData
        liveData = (MutableLiveData<Integer>) timerWithLiveDataViewModel.getCurrentSecond();

        //通过LiveData.observe()观察ViewModel中数据的变化
        liveData.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer second) {
                //收到回调后更新UI界面
                ((TextView)findViewById(R.id.tvTime)).setText("TIME" + second);
            }
        });

        //重置计时器
        findViewById(R.id.btnResetTime).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //通过LiveData.setValue()/LiveData.postValue()
                //完成对ViewModel中数据的更新
                liveData.setValue(0);
            }
        });

        //计时开始
        timerWithLiveDataViewModel.startTiming();
    }
}